package com.kintreda.tools.utils;


import cn.hutool.core.util.URLUtil;
import com.kintreda.common.config.exception.CommonBaseErrorCode;
import com.kintreda.common.config.exception.CommonBaseException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @author jing.huang
 * @function
 * @date 2018年1月10日
 * @version
 */
@Service
public class AesUtils {

    private static String aesKey;
    @Value("${platform.aesKey}")
    public void setAesKey(String aesKey) {
        AesUtils.aesKey = aesKey;
    }

    /**
     * 算法
     */
    private static final String CBC = "AES/CBC/PKCS5Padding";
    private static final String ECB = "AES/ECB/PKCS5Padding";
    /**
     * 静态常量
     */
    private static final String AES = "AES";


    /**
     * 将字符串【AES加密】为base 64 code
     *
     * @param content 待加密的内容
     * @return 加密后的base 64 code
     */
    public static String aesEncrypt(String content,String iv) {
        try {
            // 初始化为加密模式的密码器
            Cipher cipher = null;
            if (StringUtils.isNoneBlank(iv)){
                cipher = Cipher.getInstance(CBC);
                IvParameterSpec ivString = new IvParameterSpec(iv.getBytes("UTF-8"));
                cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey.getBytes(), AesUtils.AES),ivString);
            }else{
                cipher = Cipher.getInstance(ECB);
                cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey.getBytes(), AesUtils.AES));
            }
            byte[] bytes = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            // 使用base64解码
            return Base64.encodeBase64String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonBaseException(CommonBaseErrorCode.SYS_ERROR.setErrMsg("加密失败"));
        }
    }

    /**
     * 将base 64 code 【AES解密】为字符串
     *
     * @param encryptStr 待解密的base 64 code
     * @param iv iv
     * @return 解密后的String
     */
    public static String aesDecrypt(String encryptStr,String iv) {
        try {
            if (StringUtils.isEmpty(encryptStr)) {
                return null;
            }
            if (encryptStr.contains("%")){
                encryptStr = URLUtil.decode(encryptStr);
            }
            // 将字符串转为byte，返回解码后的byte[]
            byte[] encryptBytes = Base64.decodeBase64(encryptStr);
            // 初始化为解密模式的密码器
            Cipher cipher = null;
            if (StringUtils.isNoneBlank(iv)){
                cipher = Cipher.getInstance(CBC);
                IvParameterSpec ivString = new IvParameterSpec(iv.getBytes("UTF-8"));
                System.out.println(aesKey);
                System.out.println(AesUtils.aesKey);
                cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey.getBytes(), AesUtils.AES),ivString);
            }else{
                cipher = Cipher.getInstance(ECB);
                cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey.getBytes(), AesUtils.AES));
            }
            byte[] decryptBytes = cipher.doFinal(encryptBytes);

            return new String(decryptBytes);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CommonBaseException(CommonBaseErrorCode.SYS_ERROR.setErrMsg("解密失败"));
        }
    }

    /**将二进制转换成16进制
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**将16进制转换为二进制
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}